package com.hzc.springchan.config.threadpool;

import com.hzc.springchan.constant.System;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置类
 * @author chen990627
 * @date 2022/10/14
 */
@Configuration
public class CThreadPoolConfig {
    /**
     * mark 线程池使用业务场景：
     *  1. 消息推送
     *  2. 保存操作记录
     * @return
     */
    @Bean(System.Executor.TASK_EXECUTOR)
    public Executor taskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(50);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("springchan-taskExecutor-");
        // 直接在主线程运行被拒绝的任务，若执行线程已经关闭，则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程最大执行时间，如果超过这个时间就会强行销毁线程，以确保应用最后不会被阻塞
        executor.setAwaitTerminationSeconds(60);

        return executor;
    }
}
